<?php

class Wall_Widget_FeedController extends Engine_Content_Widget_Abstract
{

    public function indexAction()
    {
        $viewer = Engine_Api::_()->user()->getViewer();
        $wall_settings = Engine_Api::_()->getApi('settings', 'core')->wall;
        $autoload_feed_limit = intval($wall_settings['autoload']['limit']);

        $subject = null;
        if (Engine_Api::_()->core()->hasSubject())
        {
            // Get subject
            $subject = Engine_Api::_()->core()->getSubject();
            if (!$subject->authorization()->isAllowed($viewer, 'view'))
            {
                return $this->setNoRender();
            }
        }

        $this->view->friendUsers = $friendUsers = Engine_Api::_()->wall()->getViewerFriends($viewer);

        $request = Zend_Controller_Front::getInstance()->getRequest();
        $actionTable = Engine_Api::_()->getDbtable('actions', 'wall');

        // Get some options
        $countAutoload = $request->getParam('countAutoload', 0);
        $this->view->countAutoload = $countAutoload + 1;
        $this->view->feedOnly = $feedOnly = $request->getParam('feedOnly', false);
        $this->view->length = $length = $request->getParam('limit', Engine_Api::_()->getApi('settings', 'core')->getSetting('activity.length', 15));
        $this->view->itemActionLimit = $itemActionLimit = Engine_Api::_()->getApi('settings', 'core')->getSetting('activity.userlength', 20);

        $this->view->updateSettings = Engine_Api::_()->getApi('settings', 'core')->getSetting('activity.liveupdate');
        $this->view->viewAllLikes = $request->getParam('viewAllLikes', $request->getParam('show_likes', false));
        $this->view->viewAllComments = $request->getParam('viewAllComments', $request->getParam('show_comments', false));
        $this->view->getUpdate = $request->getParam('getUpdate');
        $this->view->checkUpdate = $request->getParam('checkUpdate');
        $this->view->action_id = (int) $request->getParam('action_id');
        $this->view->enable_privacy = true;
        $this->view->wall_settings = $wall_settings;
        $this->view->autoload_feed_limit = $autoload_feed_limit;

        if (!$viewer->getIdentity())
        {
            // disable privacy when user is not logged in
            $this->view->enable_privacy = false;
        }

        if ($feedOnly)
        {
            $this->getElement()->removeDecorator('Title');
            $this->getElement()->removeDecorator('Container');
        }
        if ($length > 50)
        {
            $this->view->length = $length = 50;
        }

        $filter_type = $this->_getParam('filter_type', 'default');
        $filter_id = $this->_getParam('filter_id', null);
        $this->view->filter_type = $filter_type;
        $this->view->filter_id = $filter_id;

        // Get config options for activity
        $config = array(
            'action_id' => (int) $request->getParam('action_id'),
            'max_id' => (int) $request->getParam('maxid'),
            'min_id' => (int) $request->getParam('minid'),
            'limit' => (int) $length,
            //'ajax_call' => false,
            'filter_type' => $filter_type,
            'filter_id' => $filter_id,
        );

        // Pre-process feed items
        $selectCount = 0;
        $itemCount = 0;
        //$nextid = null;
        $firstid = null;
        $tmpConfig = $config;
        $activity = array();
        $endOfFeed = false;
        $friendRequests = array();
        $itemActionCounts = array();
        $the_next_id = null;
        $end_of_feed = FALSE;
        $enabledModules = Engine_Api::_()->getDbtable('modules', 'core')->getEnabledModuleNames();
        do
        {
            // Get current batch
            $actions = null;

            if (!empty($subject))
            {
                $actions = $actionTable->getActivityAbout($subject, $viewer, $tmpConfig, $the_next_id, $end_of_feed);
                // Not show privacy box
                if (isset($viewer->user_id) && $subject->user_id != $viewer->user_id)
                    $this->view->enable_privacy = false;
            } else
            {
                $actions = $actionTable->getActivity($viewer, $tmpConfig, $the_next_id, $end_of_feed);
            }

            $selectCount++;
            // Are we at the end?
            $endOfFeed = ($end_of_feed != null) ? $end_of_feed : false;
//            if (count($actions) < $length || count($actions) <= 0)
//            {
//                $endOfFeed = true;
//            }
            // Pre-process
            if (count($actions) > 0)
            {
                foreach ($actions as $action)
                {
                    // get next id
//                    if (null === $nextid || $action->action_id <= $nextid)
//                    {
//                        $nextid = $action->action_id - 1;
//                    }
                    // get first id
                    if (null === $firstid || $action->action_id > $firstid)
                    {
                        $firstid = $action->action_id;
                    }
                    // skip disabled actions
                    if (!$action->getTypeInfo()->enabled)
                        continue;
                    // skip items with missing items
                    if (!$action->getSubject() || !$action->getSubject()->getIdentity())
                        continue;
                    if (!$action->getObject() || !$action->getObject()->getIdentity())
                        continue;
                    // track/remove users who do too much (but only in the main feed)
                    if (empty($subject))
                    {
                        $actionSubject = $action->getSubject();
                        $actionObject = $action->getObject();
                        if (!isset($itemActionCounts[$actionSubject->getGuid()]))
                        {
                            $itemActionCounts[$actionSubject->getGuid()] = 1;
                        }
                        else if ($itemActionCounts[$actionSubject->getGuid()] >= $itemActionLimit)
                        {
                            continue;
                        }
                        else
                        {
                            $itemActionCounts[$actionSubject->getGuid()]++;
                        }
                    }
                    // remove duplicate friend requests
                    if ($action->type == 'friends')
                    {
                        $id = $action->subject_id . '_' . $action->object_id;
                        $rev_id = $action->object_id . '_' . $action->subject_id;
                        if (in_array($id, $friendRequests) || in_array($rev_id, $friendRequests))
                        {
                            continue;
                        }
                        else
                        {
                            $friendRequests[] = $id;
                            $friendRequests[] = $rev_id;
                        }
                    }
                    // remove items with disabled module attachments
                    try
                    {
                        $attachments = $action->getAttachments();
                    }
                    catch (Exception $e)
                    {
                        // if a module is disabled, getAttachments() will throw an Engine_Api_Exception; catch and continue
                        continue;
                    }
                    // add to list
                    if (count($activity) <= $length)
                    {
                        $activity[] = $action;
                        if (count($activity) == $length)
                        {
                            $actions = array();
                        }
                    }
                }
            }

            // Set next tmp max_id
            if ($the_next_id)
            {
                $tmpConfig['max_id'] = $the_next_id;
            }
            if (!empty($tmpConfig['action_id']))
            {
                $actions = array();
            }
        }
        while (count($activity) < $length && $selectCount <= 10 && !$endOfFeed);
        //while (count($activity) < $length && !$endOfFeed);

        $this->view->activity = $activity;
        $this->view->activityCount = count($activity);
        $this->view->nextid = $the_next_id;
        $this->view->firstid = $firstid;

        //print_r($firstid);die;
        
        if (count($activity) == 0){
            $this->view->endOfFeed = true;
            $this->view->noFeed = true;
        } else {
            $this->view->noFeed = false;
        }
        //Fix: after check update, end of feed = true
        $this->view->endOfFeed = $endOfFeed;
        if ($filter_type != 'default'){
            if (count($activity) < $length) $this->view->endOfFeed = true;
        }
        if ($request->getParam('checkUpdate'))
        {
            $this->view->endOfFeed = false;
        }
        
        //$nofeed = $this->view->noFeed?'true':'false';
        
        // Get some other info
        if (!empty($subject))
        {
            $this->view->subjectGuid = $subject->getGuid(false);
        }

        $this->view->enableComposer = false;
        if ($viewer->getIdentity() && !$this->_getParam('action_id'))
        {
            if (!$subject || $subject->authorization()->isAllowed($viewer, 'comment'))
            {
                $this->view->enableComposer = true;
            }
        }

        // Assign the composing values
        $composePartials = array();
        foreach (Zend_Registry::get('Engine_Manifest') as $data)
        {
            if (empty($data['composer']))
            {
                continue;
            }
            foreach ($data['composer'] as $type => $config)
            {
                if (!empty($config['auth']) && !Engine_Api::_()->authorization()->isAllowed($config['auth'][0], null, $config['auth'][1]))
                {
                    continue;
                }
                $composePartials[] = $config['script'];
            }
        }
        $this->view->composePartials = $composePartials;

        $headScript = new Zend_View_Helper_HeadScript();

        $headScript->appendFile('application/modules/Wall/externals/scripts/composer.js');
        $headScript->appendFile('application/modules/Wall/externals/scripts/wall.js');
        $headScript->appendFile('application/modules/Wall/externals/scripts/scrollspy.1.2.js');
        $headScript->appendFile('application/modules/Wall/externals/scripts/jquery.tools.min.js');
        $this->view->tranlate = Zend_Registry::get('Zend_Translate');

        $headLink = new Zend_View_Helper_HeadLink();
        $headLink->prependStylesheet('application/modules/Wall/externals/styles/walltip.css');

        //Get custom lists
        $lists_table = Engine_Api::_()->getDbtable('lists', 'wall');
        $items_table = Engine_Api::_()->getDbtable('listItems', 'wall');

        $select = $lists_table->select()->where('user_id = ?', $viewer->getIdentity());
        $custom_lists = $lists_table->fetchAll($select);

        $this->view->custom_lists = $custom_lists;
    }

}
